package m.framework.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import m.Config;
import m.framework.exception.SystemException;
import m.framework.utils.FileUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

public class ControllerHolder {
	private static Logger log = LoggerFactory.getLogger(ControllerHolder.class);
	private static Map<String, BaseController> controllerMap;

	private static Map<String, BaseController> createMap() {
		Map map = new HashMap();
		String root = Config.getClassPath();
		log.debug("开始在"+root+"下查找controller");
		List<File> file = FileUtil.getAllFile(root);
		for (File f : file) {
			String path = f.getAbsolutePath();
			if (!path.endsWith("Controller.class")) {
				continue;
			}
		
			path = path.replaceAll("/", ".").replaceAll("\\\\", ".");
			int begin = path.indexOf("."+Config.PACKAGE_ROOT+".")+1;
			int end = path.lastIndexOf('.');
			String className = path.substring(begin, end);
			try {
				Class clazz=Class.forName(className);
				if(clazz.getAnnotation(Controller.class)==null){
					continue;
				}
				BaseController bc = (BaseController)clazz.newInstance();
				log.info("新增controller:{}--{}", bc.getName().toLowerCase(), className);
				map.put(bc.getName().toLowerCase(), bc);
			} catch (Exception e) {
				throw new SystemException("创建controller失败:" + className, e);
			}
		}
		
		return map;
	}

	private static Map<String, BaseController> controllerMap() {
		if (controllerMap == null) {
			controllerMap = createMap();
		}
		return controllerMap;
	}

	public static BaseController get(String name) {
		return (BaseController) controllerMap().get(name);
	}

	public static List<BaseController> getAll() {
		return new ArrayList(controllerMap().values());
	}

}
